// 定义塔数据结构
interface Tower {
  id: string;
  project_code: string;
  s_project_code: string;
  section_code: string;
  tower_name: string;
  lon: string;
  lat: string;
  last_tower: string;
  [key: string]: any; // 允许其他字段存在
}

// GeoJSON 类型
interface GeoJSONFeature {
  type: "Feature";
  geometry: {
    type: "LineString";
    coordinates: [number, number][];
  };
  properties: {
    name: string;
    segmentIndex: number;
  };
}

interface GeoJSONFeatureCollection {
  type: "FeatureCollection";
  features: GeoJSONFeature[];
}

// 主函数
export function towersToGeoJSON(towers: Tower[]): GeoJSONFeatureCollection {
  // 构建索引：tower_name -> 数据
  const towerMap: Record<string, Tower> = {};
  towers.forEach(t => {
    towerMap[t.tower_name] = t;
  });

  // 找所有起点：没有其他塔指向它的塔
  const allLast = new Set(towers.map(t => t.last_tower).filter(Boolean));
  const startTowers = towers.filter(t => !allLast.has(t.tower_name));

  if (!startTowers.length) {
    throw new Error("未找到起点塔，请检查数据");
  }

  const features: GeoJSONFeature[] = [];

  startTowers.forEach((start, idx) => {
    const coords: [number, number][] = [];
    let current: Tower | undefined = start;

    while (current) {
      const lon = parseFloat(current.lon);
      const lat = parseFloat(current.lat);
      coords.push([lon, lat]);

      const nextName:string = current.last_tower;
      current = nextName ? towerMap[nextName] : undefined;
    }

    if (coords.length > 1) {
      features.push({
        type: "Feature",
        geometry: {
          type: "LineString",
          coordinates: coords
        },
        properties: {
          name: `Transmission Line Segment ${idx + 1}`,
          segmentIndex: idx + 1
        }
      });
    }
  });

  return {
    type: "FeatureCollection",
    features
  };
}
